package com.ruoyi.web.controller.demo;

import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.generator.service.IFromBuildConfigService;

import com.ruoyi.demo.domain.TDemo;
import com.ruoyi.demo.service.ITDemoService;

/**
 * 测试DemoController
 *
 * @author ZGL
 * @date 2024-09-30 14:12:25
 */
@RestController
@RequestMapping("/demo/TDemo")
public class TDemoController extends BaseController
{
    @Autowired
    private ITDemoService tDemoService;

    @Autowired
    private IFromBuildConfigService fromBuildConfigService;

    /**
     * 获取字段信息
     * @return
     */
    @GetMapping("/init")
    public AjaxResult getFieldInfo(){
        return fromBuildConfigService.getColumnConfigByTableName("t_demo");
    }

    /**
     * 查询测试Demo列表
     */
    @PreAuthorize("@ss.hasPermi('demo:TDemo:list')")
    @GetMapping("/list")
    public TableDataInfo list(TDemo tDemo){
        try{
            PageDomain pageDomain = TableSupport.buildPageRequest();
            Page<TDemo> page=new Page<>(pageDomain.getPageNum(),pageDomain.getPageSize());
            QueryWrapper<TDemo> queryWrapper = getQueryWrapper(tDemo);
            //默认按创建时间倒排序
            ArrayList<OrderItem> orderItems = new ArrayList<>();
            orderItems.add(OrderItem.desc("create_time"));
            page.addOrder(orderItems);
            tDemoService.page(page,queryWrapper);
            return getDataTable(page);
        }catch (Exception e){
            logger.error("TDemoController接口list异常",e);
            return null;
        }
    }

    /**
     * 获取测试Demo详细信息
     */
    @PreAuthorize("@ss.hasPermi('demo:TDemo:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id,
                              @RequestParam(value = "clientType",defaultValue = "PC") String clientType){
        try{
            Map<String,Object> result=new HashMap<>();
            //表单数据
            result.put("data",tDemoService.getById(id));
            //表单设计字段配置信息
            result.put("formBuildConfig",fromBuildConfigService.getFormBuildConfig("TDemo",clientType));
            //返回结果
            return AjaxResult.success(result);
        }catch (Exception e){
            logger.error("TDemoController接口getInfo异常",e);
            return AjaxResult.error("获取异常");
        }
    }

    /**
     * 新增测试Demo
     */
    @PreAuthorize("@ss.hasPermi('demo:TDemo:add')")
    @Log(tableName = "t_demo", title = "测试Demo", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TDemo tDemo){
        try{
            return toAjax(tDemoService.insertTDemo(tDemo));
        }catch (Exception e){
            logger.error("TDemoController接口add异常",e);
            return AjaxResult.error("操作失败");
        }
    }

    /**
     * 修改测试Demo
     */
    @PreAuthorize("@ss.hasPermi('demo:TDemo:edit')")
    @Log(tableName = "t_demo", title = "测试Demo", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TDemo tDemo){
        try{
            return toAjax(tDemoService.update(tDemo));
        }catch (Exception e){
            logger.error("TDemoController接口edit异常",e);
            return AjaxResult.error("操作失败");
        }
    }

    /**
     * 删除测试Demo
     */
    @PreAuthorize("@ss.hasPermi('demo:TDemo:remove')")
    @Log(tableName = "t_demo", title = "测试Demo", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids){
        try{
            return toAjax(tDemoService.deleteTDemoByIds(ids));
        }catch (Exception e){
            logger.error("TDemoController接口remove异常",e);
            return AjaxResult.error("操作失败");
        }
    }

    /**
     * 导入数据
     */
    @Log(tableName = "t_demo", title = "测试Demo", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('demo:TDemo:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<TDemo> util = new ExcelUtil<TDemo>(TDemo.class);
        List<TDemo> dataList = util.importExcel(file.getInputStream());
        int successCount=0;
        for(TDemo item : dataList){
            if(tDemoService.save(item)){
                successCount++;
            }
        }
        String result=StringUtils.format("导入成功条数:{}，失败条数：{}",successCount,(dataList.size()-successCount));
        return AjaxResult.success(result);
    }

    /**
     * 导入横版
     */
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        ExcelUtil<TDemo> util = new ExcelUtil<TDemo>(TDemo.class);
        util.importTemplateExcel(response,"测试Demo");
    }

    /**
     * 导出测试Demo列表
     */
    @PreAuthorize("@ss.hasPermi('demo:TDemo:export')")
    @Log(tableName = "t_demo", title = "测试Demo", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TDemo tDemo){
        QueryWrapper<TDemo> queryWrapper = getQueryWrapper(tDemo);
        ExcelUtil<TDemo> util = new ExcelUtil<TDemo>(TDemo.class);
        util.exportExcel(response,tDemoService.list(queryWrapper), "测试Demo");
    }

}
